/*
 * Copyright (c) 2020. www.sonsure.com Inc. All rights reserved.
 * You may obtain more information at
 *
 *   http://www.sonsure.com
 *
 * Designed By Selfly Lee (selfly@live.com)
 */

package com.sonsure.dustman.test.jdbc.extension.executor;

import com.sonsure.dustman.jdbc.command.batch.BatchExecutableCmd;
import com.sonsure.dustman.jdbc.command.build.ExecutableCmd;
import com.sonsure.dustman.jdbc.persist.AbstractPersistExecutor;
import lombok.Setter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;

import java.util.List;
import java.util.Map;

/**
 * Created by liyd on 17/4/12.
 */
@Setter
public class HibernatePersistExecutor extends AbstractPersistExecutor {

    private SessionFactory sessionFactory;


    @Override
    public Object insert(final ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public List<?> findList(ExecutableCmd executableCmd) {
        Session session = sessionFactory.openSession();
        NativeQuery<?> nativeQuery = session.createNativeQuery(executableCmd.getCommand(), executableCmd.getResultType());
        List<Object> parameters = executableCmd.getParsedParameterValues();
        for (int i = 0; i < parameters.size(); i++) {
            nativeQuery.setParameter(i + 1, parameters.get(i));
        }
        List<?> resultList = nativeQuery.getResultList();
        session.close();
        return resultList;
    }

    @Override
    protected Object doExecuteInConnection(ExecutableCmd executableCmd) {
        Session session = sessionFactory.openSession();
        String r = (String) session.doReturningWork(connection -> executableCmd.getExecutionFunction().apply(connection));
        session.close();
        return r;
    }

    @Override
    public Object findOne(ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public Map<String, Object> findOneForMap(ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public List<Map<String, Object>> findListForMap(ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public Object findOneForScalar(ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public List<?> findListForScalar(ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public int update(ExecutableCmd executableCmd) {
        return 0;
    }

    @Override
    public int delete(ExecutableCmd executableCmd) {
        return 0;
    }

    @Override
    protected <T> Object batchUpdate(BatchExecutableCmd<T> commandContext) {
        return null;
    }

    @Override
    protected Object doExecutionInRaw(ExecutableCmd executableCmd) {
        return null;
    }

    @Override
    public Object doExecute(ExecutableCmd executableCmd) {
        return this.update(executableCmd);
    }

    @Override
    protected Object doExecuteScript(ExecutableCmd executableCmd) {
        return null;
    }

}
